<template>
  <div class="department-container">
    <!-- 页面标题和操作区域 -->
    <div class="page-header">
      <h1>部门管理</h1>
      <p>管理系统部门结构，每个部门可以包含子部门和用户</p>

      <div class="operation-buttons">
        <el-button type="primary" icon="el-icon-plus" @click="openAddDepartmentDialog(null)">
          新增根部门
        </el-button>
        <el-button icon="el-icon-refresh" @click="refreshData">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧部门树 -->
      <div class="department-tree-panel">
        <div class="panel-header">
          <span>部门结构</span>
          <el-input
            v-model="departmentFilterText"
            placeholder="搜索部门"
            prefix-icon="el-icon-search"
            size="small"
            clearable
          ></el-input>
        </div>

        <div class="tree-container">
          <el-tree
            ref="departmentTree"
            :data="departmentTreeData"
            :props="departmentTreeProps"
            :filter-node-method="filterDepartmentNode"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="handleDepartmentNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span class="node-label">
                <i :class="getDepartmentIcon(data)"></i>
                {{ node.label }}
              </span>
              <span class="node-actions">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  @click="() => openAddDepartmentDialog(data)"
                >
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click="() => openEditDepartmentDialog(data)"
                >
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click="() => deleteDepartment(data)"
                >
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </div>

      <!-- 右侧部门详情和用户列表 -->
      <div class="department-detail-panel">
        <div v-if="selectedDepartment" class="detail-content">
          <!-- 部门基本信息 -->
          <div class="department-info">
            <h2>
              <i :class="getDepartmentIcon(selectedDepartment)"></i>
              {{ selectedDepartment.name }}
            </h2>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">部门编码:</span>
                <span class="value">{{ selectedDepartment.code || 'N/A' }}</span>
              </div>
              <div class="info-item">
                <span class="label">负责人:</span>
                <span class="value">{{ selectedDepartment.manager || '未指定' }}</span>
              </div>
              <div class="info-item">
                <span class="label">部门描述:</span>
                <span class="value">{{ selectedDepartment.description || '暂无描述' }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户数量:</span>
                <span class="value">{{ selectedDepartmentUsers.length }} 人</span>
              </div>
            </div>
          </div>

          <!-- 用户列表 -->
          <div class="user-list-section">
            <div class="section-header">
              <h3>部门成员 ({{ selectedDepartmentUsers.length }})</h3>
              <el-button
                type="primary"
                icon="el-icon-user"
                size="small"
                @click="openAddUserDialog"
              >
                添加成员
              </el-button>
            </div>

            <div class="user-table">
              <el-table
                :data="selectedDepartmentUsers"
                stripe
                style="width: 100%"
                empty-text="该部门暂无成员"
              >
                <el-table-column prop="username" label="姓名" width="120"></el-table-column>
                <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
                <el-table-column prop="position" label="职位" width="150"></el-table-column>
                <el-table-column label="状态" width="100">
                  <template slot-scope="scope">
                    <el-tag
                      :type="scope.row.status === 'active' ? 'success' : 'danger'"
                      size="small"
                    >
                      {{ scope.row.status === 'active' ? '在职' : '离职' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="joinDate" label="入职日期" width="120"></el-table-column>
                <el-table-column label="操作" width="150">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="removeUserFromDepartment(scope.row)"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <i class="el-icon-office-building empty-icon"></i>
          <p>请从左侧选择一个部门查看详情</p>
        </div>
      </div>
    </div>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog
      :title="departmentForm.id ? '编辑部门' : '新增部门'"
      :visible.sync="departmentDialogVisible"
      width="500px"
    >
      <el-form
        :model="departmentForm"
        :rules="departmentFormRules"
        ref="departmentFormRef"
        label-width="80px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="departmentForm.code" placeholder="请输入部门编码"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="departmentForm.manager" placeholder="请输入负责人姓名"></el-input>
        </el-form-item>
        <el-form-item label="部门类型" prop="type">
          <el-select v-model="departmentForm.type" placeholder="请选择部门类型" style="width: 100%">
            <el-option
              v-for="type in departmentTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            v-model="departmentForm.description"
            placeholder="请输入部门描述"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="departmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDepartment">保存</el-button>
      </div>
    </el-dialog>

    <!-- 添加用户到部门对话框 -->
    <el-dialog
      title="添加成员到部门"
      :visible.sync="addUserDialogVisible"
      width="700px"
    >
      <div class="add-user-dialog">
        <div class="available-users">
          <h4>可选用户</h4>
          <el-table
            :data="rightUserList"
            stripe
            style="width: 100%"
            @selection-change="handleUserSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="username" label="姓名" width="120"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
            <el-table-column prop="position" label="职位" width="150"></el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status === 'active' ? 'success' : 'danger'"
                  size="small"
                >
                  {{ scope.row.status === 'active' ? '在职' : '离职' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUsersToDepartment">添加选中用户</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList,getUserListByDeptId,insert,update,deleteById,insertUserList,removeUser } from '@/api/dept'
import { getRightUserList } from '@/api/user'
import data from '../pdf/content';
export default {
  name: 'DepartmentManagement',
  data() {
    return {
      // 部门树数据
      departmentTreeData: [],
       rightUserList:[],
      // 选中的部门
      selectedDepartment: null,

      // 部门树配置
      departmentTreeProps: {
        children: 'children',
        label: 'name'
      },

      // 部门搜索文本
      departmentFilterText: '',

      // 对话框控制
      departmentDialogVisible: false,
      addUserDialogVisible: false,

      // 部门表单
      departmentForm: {
        id: '',
        name: '',
        code: '',
        manager: '',
        type: '',
        description: '',
        parentId: null
      },

      // 表单验证规则
      departmentFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择部门类型', trigger: 'change' }
        ]
      },

      // 部门类型选项
      departmentTypes: [
        { value: 'company', label: '公司' },
        { value: 'department', label: '部门' },
      ],

      // 所有用户数据
      allUsers: [],


      // 选中的用户（用于添加到部门）
      selectedUsers: []
    }
  },

  computed: {
    // 当前选中部门的用户列表
    selectedDepartmentUsers() {
      if (!this.selectedDepartment) return [];
      // 在实际应用中，这里应该是从API获取该部门的用户
      // 这里我们模拟根据部门ID过滤用户
      return this.allUsers.filter(user =>
        user.deptId === this.selectedDepartment.id
      );
    },

    // 可添加到部门的用户（不在当前部门的用户）
    availableUsers() {
      if (!this.selectedDepartment) return [];

      // 过滤出不在当前部门的用户
      return this.allUsers.filter(user =>
        user.departmentId !== this.selectedDepartment.id
      );
    }
  },

  watch: {
    // 监听部门搜索文本变化，过滤部门树
    departmentFilterText(val) {
      this.$refs.departmentTree.filter(val);
    }
  },
//   created(){
//  this.getRightUserList();
//   },

  mounted() {
     this.getRightUserList();
    this.getDeptList();
    // this.loadUserData();
    this.getUserList();

  },

  methods: {
    async removeUser(data){
      const res=  await removeUser(data)
      if(res.code===200){
        this.getRightUserList();
        this.getUserList();
        this.$message({
          message: '移除成功',
          type: 'success'
        });
      }
    },
    async deleteById(id){
      const res=  await deleteById(id)
      if(res.code===200){
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        });
      }
    },

       async insertUserList(data){
      const res=  await insertUserList(data)
        if(res.code===200){
            this.getRightUserList();
    // this.loadUserData();
    this.getUserList();

       this.$message({
        message: '添加成功',
        type: 'success'
      });
      }
    },
      async getRightUserList(){
       const res= await getRightUserList()
       this.rightUserList=res.data
    },
     async getDeptList(){
      const res=  await deptList()
       this.departmentTreeData=res.data
    },
     async insert(dept){
      const res=  await insert(dept)
        if(res.code===200){
            this.$message({
            message:res.message,
            type: 'success'
           });
            this.departmentDialogVisible = false;
            this.addDepartmentToTree(this.departmentTreeData, this.departmentForm);
            // this.getList()
      }else{
         this.$message({
        message:res.message,
        type: 'error'
      });
      }
    },
     async update(dept){
      const res=  await update(dept)
        if(res.code===200){
        this.$message({
         message:res.message,
        type: 'success'
      });
       this.departmentDialogVisible = false;
        this.updateDepartmentInTree(this.departmentTreeData, this.departmentForm);
      }else{
         this.$message({
        message:res.message,
        type: 'error'
      });
      }
    },
      async getUserList(){
      const res=  await getUserListByDeptId()
       this.allUsers=res.data
    },
    // 加载部门数据
    loadDepartmentData() {
      // 模拟API调用获取部门数据
      setTimeout(() => {

      }, 500);
    },
    refreshData() {
      this.loadDepartmentData();
      this.loadUserData();
      this.$message({
        message: '数据已刷新',
        type: 'success'
      });
    },

    // 过滤部门节点
    filterDepartmentNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 处理部门节点点击
    handleDepartmentNodeClick(data) {
      this.selectedDepartment = data;
    },

    // 获取部门图标
    getDepartmentIcon(department) {
      const iconMap = {
        'company': 'el-icon-office-building',
        'division': 'el-icon-s-management',
        'department': 'el-icon-s-home',
        'team': 'el-icon-user-solid'
      };
      return iconMap[department.type] || 'el-icon-folder';
    },

    // 打开添加部门对话框
    openAddDepartmentDialog(parentDepartment) {
      this.departmentForm = {
        id: '',
        name: '',
        code: '',
        manager: '',
        type: 'department',
        description: '',
        parentId: parentDepartment ? parentDepartment.id : null
      };
      this.departmentDialogVisible = true;

      // 清除表单验证
      if (this.$refs.departmentFormRef) {
        this.$refs.departmentFormRef.clearValidate();
      }
    },

    // 打开编辑部门对话框
    openEditDepartmentDialog(department) {
      this.departmentForm = { ...department };
      this.departmentDialogVisible = true;

      // 清除表单验证
      if (this.$refs.departmentFormRef) {
        this.$refs.departmentFormRef.clearValidate();
      }
    },

    // 保存部门
    saveDepartment() {
      this.$refs.departmentFormRef.validate((valid) => {
        if (valid) {
          if (this.departmentForm.id) {
          // 更新部门
            this.update(this.departmentForm)

          } else {
            // 添加新部门
            this .insert(this.departmentForm)

          }

        } else {
          this.$message({
            message: '请检查表单填写是否正确',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 在树中更新部门
    updateDepartmentInTree(nodes, department) {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === department.id) {
          Object.assign(nodes[i], department);
          return true;
        }
        if (nodes[i].children && this.updateDepartmentInTree(nodes[i].children, department)) {
          return true;
        }
      }
      return false;
    },

    // 在树中添加部门
    addDepartmentToTree(nodes, department) {
      // 如果是根部门
      if (!department.parentId) {
        const newId = this.getNextDepartmentId();
        nodes.push({
          id: newId,
          name: department.name,
          code: department.code,
          manager: department.manager,
          type: department.type,
          description: department.description,
          children: []
        });
        return;
      }

      // 查找父部门并添加子部门
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === department.parentId) {
          if (!nodes[i].children) {
            nodes[i].children = [];
          }
          const newId = this.getNextDepartmentId();
          nodes[i].children.push({
            id: newId,
            name: department.name,
            code: department.code,
            manager: department.manager,
            type: department.type,
            description: department.description,
            children: []
          });
          return;
        }
        if (nodes[i].children) {
          this.addDepartmentToTree(nodes[i].children, department);
        }
      }
    },

    // 获取下一个部门ID
    getNextDepartmentId() {
      let maxId = 0;
      const findMaxId = (nodes) => {
        nodes.forEach(node => {
          if (node.id > maxId) maxId = node.id;
          if (node.children) findMaxId(node.children);
        });
      };
      findMaxId(this.departmentTreeData);
      return maxId + 1;
    },

    // 删除部门
    deleteDepartment(department) {
      this.$confirm(`确定要删除部门 "${department.name}" 吗？此操作将删除该部门及其所有子部门`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteById(department.id)
        this.removeDepartmentFromTree(this.departmentTreeData, department.id);
        // 如果删除的是当前选中的部门，清空选中状态
        if (this.selectedDepartment && this.selectedDepartment.id === department.id) {
          this.selectedDepartment = null;
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 从树中删除部门
    removeDepartmentFromTree(nodes, departmentId) {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === departmentId) {
          nodes.splice(i, 1);
          return true;
        }
        if (nodes[i].children && this.removeDepartmentFromTree(nodes[i].children, departmentId)) {
          return true;
        }
      }
      return false;
    },

    // 打开添加用户对话框
    openAddUserDialog() {
      if (!this.selectedDepartment) {
        this.$message({
          message: '请先选择一个部门',
          type: 'warning'
        });
        return;
      }
      this.selectedUsers = [];
      this.addUserDialogVisible = true;
    },

    // 处理用户选择变化
    handleUserSelectionChange(selection) {
      this.selectedUsers = selection;
    },

    // 添加用户到部门
    addUsersToDepartment() {
      if (this.selectedUsers.length === 0) {
        this.$message({
          message: '请至少选择一个用户',
          type: 'warning'
        });
        return;
      }else{
         const paramData={
          userList:this.selectedUsers,
          deptId:this.selectedDepartment.id
        }
         this.insertUserList(paramData)
      }

      // 更新用户的部门ID
      this.selectedUsers.forEach(user => {
        user.departmentId = this.selectedDepartment.id;
      });

      this.addUserDialogVisible = false;
      // this.$message({
      //   message: `成功添加 ${this.selectedUsers.length} 个用户到部门`,
      //   type: 'success'
      // });
    },

    // 编辑用户
    editUser(user) {
      this.$message({
        message: `编辑用户 ${user.name}`,
        type: 'info'
      });
      // 在实际应用中，这里应该打开用户编辑对话框
    },

    // 从部门中移除用户
    removeUserFromDepartment(user) {
      this.$confirm(`确定要将用户 "${user.username}" 从部门中移除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data={
          userId:user.id,
          deptId:this.selectedDepartment.id
        }
        this.removeUser(data)
        // user.departmentId = null;
        // this.$message({
        //   type: 'success',
        //   message: '用户已从部门中移除!'
        // });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    }
  }
}
</script>

<style >
.department-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;

  h1 {
    font-size: 24px;
    color: #303133;
    margin-bottom: 8px;
  }

  p {
    font-size: 14px;
    color: #606266;
    margin-bottom: 20px;
  }
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
}

.department-tree-panel {
  width: 320px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;

  .panel-header {
    padding: 15px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-weight: bold;
      color: #303133;
    }

    .el-input {
      width: 150px;
    }
  }

  .tree-container {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .node-label {
    display: flex;
    align-items: center;

    i {
      margin-right: 5px;
      color: #409EFF;
    }
  }

  .node-actions {
    display: none;
  }

  &:hover .node-actions {
    display: block;
  }
}

.department-detail-panel {
  flex: 1;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
}

.department-info {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e6e6e6;

  h2 {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    color: #303133;

    i {
      margin-right: 10px;
      color: #409EFF;
      font-size: 24px;
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;

    .info-item {
      display: flex;

      .label {
        width: 80px;
        color: #909399;
        font-size: 14px;
      }

      .value {
        flex: 1;
        color: #303133;
        font-size: 14px;
      }
    }
  }
}

.user-list-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    h3 {
      color: #303133;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;

  .empty-icon {
    font-size: 60px;
    margin-bottom: 20px;
    color: #c0c4cc;
  }

  p {
    font-size: 16px;
  }
}

.add-user-dialog {
  .available-users {
    h4 {
      margin-bottom: 15px;
      color: #303133;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>
